<template>
  <div class="add-good">
    <div class="navigation">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>商品列表</el-breadcrumb-item>
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card class="box-card">
      <el-alert
        title="添加商品信息"
        type="info"
        show-icon
        :closable="false"
        show-icon
      >
      </el-alert>

      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        label-position="top"
      >
        <el-tabs
          :tab-position="tabPosition"
          v-model="activeIndex"
          :before-leave="toggleTabs"
          @tab-click="selectTab"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="ruleForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                v-model="ruleForm.goods_price"
                min="1"
                type="Number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="ruleForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="ruleForm.goods_number"
                min="1"
                type="Number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                :options="categoryList"
                :props="levelProps"
                expand-trigger="hover"
                v-model="ruleForm.goods_cat"
                @change="selectCate"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in paramList"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="checkboxItem"
                  border
                  v-for="(checkboxItem, index) in item.attr_vals"
                  :key="index"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in StaticProperty"
              :key="index"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action 图片要上传的地址 -->
            <!-- headers 设置请求头 -->
            <el-upload
              class="upload-demo"
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="setHeader"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 文本编辑器 -->
            <quill-editor v-model="ruleForm.goods_introduce">
              <!-- :options="editorOption"
              @blur="onEditorBlur($event)"
              @focus="onEditorFocus($event)"
              @change="onEditorChange($event)" -->
            </quill-editor>

            <el-button class="add-btn" type="primary" @click="finishAdd">
              添加商品
            </el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="prePicVisible" width="60%">
      <img class="pre-pic" :src="previewPic" alt="" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "AddGood",
  data() {
    return {
      // 步骤条的下标
      activeIndex: 0,
      // 设置tab选择卡在左边位置
      tabPosition: "left",

      ruleForm: {
        goods_name: "",
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        goods_cat: [],
        pics: [],

        // 商品内容描述
        goods_introduce: "",

        // 包含动态参数和静态属性
        attrs: [],
      },
      rules: {
        goods_name: [
          {
            required: true,
            message: "请输入商品名称",
            trigger: "blur",
          },
        ],
        goods_price: [
          {
            required: true,
            message: "请输入商品价格",
            trigger: "blur",
          },
        ],
        goods_weight: [
          {
            required: true,
            message: "请输入商品重量",
            trigger: "blur",
          },
        ],
        goods_number: [
          {
            required: true,
            message: "请输入商品数量",
            trigger: "blur",
          },
        ],
        goods_cat: [
          {
            required: true,
            message: "请选择商品分类",
            trigger: "blur",
          },
        ],
      },

      // 分类列表
      categoryList: [],
      levelProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },

      // 商品参数列表
      paramList: [],

      // 商品属性列表
      StaticProperty: [],

      // 设置请求头 token
      setHeader: {
        Authorization: window.sessionStorage.getItem("token"),
      },

      // 预览图片
      previewPic: "",
      // 是否展示预览图片的对话框
      prePicVisible: false,
    };
  },

  created() {
    this.getCateData();
  },
  methods: {
    // 获取分类列表数据
    getCateData() {
      this.axios({
        method: "get",
        url: "categories",
        params: {
          type: 3,
        },
      })
        .then((res) => {
          
          if (res.data.meta.status == 200) {
            this.categoryList = res.data.data;
            
          }
        })
        .catch((err) => {
          
        });
    },
    // 级联选择器的分类选项发生变化时触发
    selectCate() {
      

      // 只能选择第三级分类
      if (this.ruleForm.goods_cat.length !== 3) {
        this.ruleForm.goods_cat = [];
        this.$message.warning("请选择第三级分类！");
      }
    },

    // 切换tab选项卡
    toggleTabs(activeName, oldActiveName) {
      // 要进入的tab下标
      
      // 要离开的tab下标
      

      if (oldActiveName === "0" && this.ruleForm.goods_name === "") {
        this.$message.error("商品名称不能为空！");
        return false;
      }

      // 当处于第一个tab选项时，且分类选项没有选中，要阻止tab切换
      if (oldActiveName === "0" && this.ruleForm.goods_cat.length !== 3) {
        this.$message.error("请先选择商品分类！");
        return false;
      }
    },

    // 选中tab
    selectTab() {
      // tab下标
      // 

      // 当activeName为1时，访问的是商品参数tab
      if (this.activeIndex === "1") {
        
        this.getGoodsParam();
      } else if (this.activeIndex === "2") {
        
        this.getStaticPropertyData();
      }
    },

    // 获取商品动态参数
    getGoodsParam() {
      this.axios({
        method: "get",
        // 要选择第三级分类，下标为2，否则获取到的是空数组
        url: `categories/${this.ruleForm.goods_cat[2]}/attributes`,
        params: {
          sel: "many",
        },
      })
        .then((res) => {
          
          if (res.data.meta.status == 200) {
            this.paramList = res.data.data;
            // 将参数attr_vals分割成数组
            this.paramList.forEach((item) => {
              
              item.attr_vals = item.attr_vals
                ? item.attr_vals.split(/[, ]+/)
                : [];
              // 

              let manyObj = {
                attr_id: item.attr_id,
                attr_value: item.attr_vals.join(" "),
              };
              this.ruleForm.attrs.push(manyObj);
            });
          }
        })
        .catch((err) => {
          
        });
    },

    // 获取商品静态属性
    getStaticPropertyData() {
      this.axios({
        method: "get",
        // 要选择第三级分类，下标为2，否则获取到的是空数组
        url: `categories/${this.ruleForm.goods_cat[2]}/attributes`,
        params: {
          sel: "only",
        },
      })
        .then((res) => {
          
          if (res.data.meta.status == 200) {
            this.StaticProperty = res.data.data;

            // 遍历静态属性，塞进attrs数组中
            this.StaticProperty.forEach(v => {
              
              let onlyObj = {
                attr_id: v.attr_id,
                attr_value: v.attr_vals,
              };
              this.ruleForm.attrs.push(onlyObj);
            });
          }
        })
        .catch((err) => {
          
        });
    },

    // 上传图片

    //点击图片名称打开预览图片的对话框
    handlePreview(file) {
      

      this.previewPic = file.response.data.url;

      // 打开预览图片的对话框
      this.prePicVisible = true;
    },

    // 预览图片
    // 移除图片
    handleRemove(file) {
      

      let picUrl = file.response.data.tmp_path;

      // 获取要移除图片的索引值
      // let index = this.ruleForm.pics.findIndex(i=>{
      // i 指向handleSuccess方法的picInfo对象的pic元素
      // 
      // })

      let index = this.ruleForm.pics.findIndex((i) => i.pic === picUrl);
      // i.pic === picUrl;

      this.ruleForm.pics.splice(index, 1);

      
      // 
    },

    // 监听图片是否上传成功
    handleSuccess(response) {
      // response 图片上传后的信息
      
      if (response.meta.status == 200) {
        let picInfo = {
          pic: response.data.tmp_path,
        };

        // 将picInfo图片路径塞进data的pics中
        this.ruleForm.pics.push(picInfo);
        
        
      }
    },

    // 完成添加商品
    finishAdd() {
      // 

      this.$refs.ruleForm.validate(async (valid) => {
        //   

        if (valid) {
          // this.ruleForm.goods_cat = this.ruleForm.goods_cat.join(",");
          let form = _.cloneDeep(this.ruleForm);
          form.goods_cat = form.goods_cat.join(',')
          // 

          

          let goodCat = JSON.parse(JSON.stringify(this.ruleForm.goods_cat));
          

          this.axios({
            method: "post",
            url: 'goods',
            data: {
             goods_name: this.ruleForm.goods_name,
            //  goods_cat: goodCat,
             goods_cat: form.goods_cat,
             goods_price: this.ruleForm.goods_price,
             goods_number: this.ruleForm.goods_number,
             goods_weight: this.ruleForm.goods_weight,
             goods_introduce: this.ruleForm.goods_introduce,
             pics: this.ruleForm.pics,
             attrs: this.ruleForm.attrs
            }
          })
            .then((res) => {
              
              if(res.data.meta.status == 201){
                this.$message.success('添加商品成功！');
                this.$router.push({name:'Goods'});
              }else{
                this.$message.error('添加商品失败！'+res.data.meta.msg);
              }
            })
            .catch((err) => {
              
            });
        } else {
          this.$message.error("请填写带*号的表单项！");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.add-good {
  margin-top: 70px;
}
.box-card {
  width: 860px;
  margin-top: 22px;
  .el-steps {
    // border: 1px solid #000;
    margin-top: 16px;
    /deep/ .el-step__title {
      font-size: 13px;
    }
  }
  .el-tabs {
    // border: 1px solid #000;
    margin-top: 16px;
    margin-left: -12px;
  }
}

.el-checkbox {
  margin-right: 10px;
}
.el-checkbox.is-bordered + .el-checkbox.is-bordered {
  // border: 1px solid #000;
  margin-left: 0;
}
.pre-pic {
  width: 100%;
}
/deep/ .ql-editor {
  min-height: 260px;
}
.add-btn {
  margin-top: 14px;
}
</style>